package storage

import (
	"context"
	"strconv"
	"strings"
	"sync"

	"github.com/minio/minio-go/v7"
	"minio.com/minio-sdk/util"
)

func PutObj(wg *sync.WaitGroup, id int, minioClient *minio.Client, file *strings.Reader) {
	defer wg.Done()
	for i := 0; i < util.OBJ_NUM; i++ {
		_, err := minioClient.PutObject(context.Background(), util.BUCKET_NAME, util.OBJ_NAME_PREFIX+strconv.Itoa(i), file, util.OBJ_SIZE, minio.PutObjectOptions{ContentType: util.CONTENT_TYPE})
		if err != nil {
			util.Logger.Println(err)
			return
		}
	}
}

func PerpareData(minioClient *minio.Client) error {
	ret := util.RandData(util.OBJ_SIZE)
	content := strings.NewReader(string(ret))

	var wg sync.WaitGroup
	wg.Add(util.GO_NUM)

	// timeStart := time.Now().UnixNano()
	// Upload the tmp file with PutObject
	for i := 0; i < util.GO_NUM; i++ {
		go PutObj(&wg, i, minioClient, content)
		// util.Logger.Println("Successfully uploaded bytes: ")
	}
	wg.Wait()
	// durationTime := ((float64)(time.Now().UnixNano() - timeStart)) / 1e9
	// logger.Printf("Successfully uploaded %s0 - %s%d of size %d\n", OBJ_NAME_PREFIX, OBJ_NAME_PREFIX, util.OBJ_NUM-1, util.OBJ_SIZE)
	// IOPS := (float64)(util.GO_NUM*util.OBJ_NUM) / (durationTime)
	// Throughput := IOPS * util.OBJ_SIZE / (1024 * 1024)
	// util.Logger.Printf("Perpare obj cost Time: %fs, Throughput: %fMB/s, IOPS: %f\n", durationTime, Throughput, IOPS)
	return nil
}
